//
//  CameraViewController.m
//  gee
//
//  Created by Gakaki on 11-5-22.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CameraViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>

@interface CameraViewController ()
static UIImage *shrinkImage(UIImage *original, CGSize size);
- (void)updateDisplay;
- (void)getMediaFromSource:(UIImagePickerControllerSourceType)sourceType;
@end

@implementation CameraViewController
@synthesize imageView;
@synthesize takePictureButton;
@synthesize moviePlayerController;
@synthesize image;
@synthesize movieURL;
@synthesize lastChosenMediaType;
@synthesize overlay;

- (void)viewDidLoad {
    if (![UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeCamera]) {
        takePictureButton.hidden = YES;
    }
    imageFrame = imageView.frame;
    
    
    [self findUniqueSavePath];
}

- (NSString *) findUniqueSavePath
{
	int i = 1;
	NSString *path; 
	do {
		// iterate until a name does not match an existing file
	    path = [NSString stringWithFormat:@"%@/Documents/IMAGE_%04d.PNG", NSHomeDirectory(), i++];
	} while ([[NSFileManager defaultManager] fileExistsAtPath:path]);
	NSLog(@"%@",path);
	return path;
}



- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self updateDisplay];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.imageView = nil;
    self.takePictureButton = nil;
    self.moviePlayerController = nil;
    self.overlay   = nil;
    
    [super viewDidUnload];
}

- (void)dealloc {
    [imageView release];
    [takePictureButton release];
    [moviePlayerController release];
    [image release];
    [movieURL release];
    [lastChosenMediaType release];
    [overlay release];
    [super dealloc];
}

- (IBAction)shootPictureOrVideo:(id)sender {
    [self getMediaFromSource:UIImagePickerControllerSourceTypeCamera];
}

- (IBAction)selectExistingPictureOrVideo:(id)sender {
    [self getMediaFromSource:UIImagePickerControllerSourceTypePhotoLibrary];
}

#pragma mark UIImagePickerController delegate methods

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; 
{
	if (!error) 
		NSLog(@"Image written to photo album");
	else
		NSLog(@"Error writing to photo album: %@", [error localizedDescription]);
	

    [self dismissModalViewControllerAnimated:YES];
		
    

}
- (void)imagePickerController:(UIImagePickerController *)picker 
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.lastChosenMediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([lastChosenMediaType isEqual:(NSString *)kUTTypeImage]) {
        UIImage *chosenImage = [info objectForKey:UIImagePickerControllerEditedImage];
        UIImage *shrunkenImage = shrinkImage(chosenImage, imageFrame.size);
        self.image = shrunkenImage;
        
        //save pic to albums
        UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
        //save in png
        NSString* file_save_path = [self findUniqueSavePath];
        [UIImagePNGRepresentation(self.image) writeToFile:file_save_path atomically:YES];
      
        // Create file manager   
        NSError *error;   
        NSFileManager *fileMgr = [NSFileManager defaultManager];   
        
        // Point to Document directory   
        NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];   
        
        // Write out the contents of home directory to console   
        NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);  

        //asihttp upload photo
        
        
        [ASIHTTPRequest setDefaultUserAgentString:@"GEE IPHONE IOS4 1.0"];
        [ASIHTTPRequest setDefaultTimeOutSeconds:10];
            
        NSURL *url = [NSURL URLWithString:@"http://192.168.2.118/gridfs_upload_image.php"];
            
            
        __block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        
        [request setPostValue:@"description" forKey:@"pic_desc"];

        [request setFile:file_save_path forKey:@"upfile"];
        
        
        [request setCompletionBlock:^{

                NSString *responseString = [request responseString];
                
                //NSData *responseData = [request responseData];
                //NSLog(@"%@",responseData);
                NSLog(@"%@",responseString);
                
                /*
                NSArray *locs = [responseString objectFromJSONString];
                NSLog(@"%@",locs);
        
                for(NSDictionary *dict in locs) {
                    NSLog(@"%@",[dict objectForKey:@"address"]);
             
                }
                
                //
                //        NSDate *date =[NSDate dateWithTimeIntervalSince1970 :[dict objectForKey:@"time"]]];
                //        
                //         NSLog(@"%@",date);
                //        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                //        
                //        [dateFormatter setDateFormat:@"yyyy年-MMM-ddd日,hh:mm:ss"];
                //        
                //        NSString *time_str = [dateFormatter stringFromDate:[NSDate date]];
                //        
                //        [dateFormatter release];
                //        
                //        NSLog(@"%@",time_str);
                */
            
            
            
            
            
                    
            
                
        }];
        [request setFailedBlock:^{
                NSError *error = [request error];
                NSLog(@"error data %@",error); 
        }];
            
            
        [request startAsynchronous];
     
        

    } else if ([lastChosenMediaType isEqual:(NSString *)kUTTypeMovie]) {
        self.movieURL = [info objectForKey:UIImagePickerControllerMediaURL];
    }
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {    
    [picker dismissModalViewControllerAnimated:YES];
}

#pragma mark  -
static UIImage *shrinkImage(UIImage *original, CGSize size) {
    CGFloat scale = [UIScreen mainScreen].scale;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGContextRef context = CGBitmapContextCreate(NULL, size.width * scale,
												 size.height * scale, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context,
					   CGRectMake(0, 0, size.width * scale, size.height * scale),
					   original.CGImage);
    CGImageRef shrunken = CGBitmapContextCreateImage(context);
    UIImage *final = [UIImage imageWithCGImage:shrunken];
    
    CGContextRelease(context);
    CGImageRelease(shrunken);	
	
    return final;
}

- (void)updateDisplay {
    if ([lastChosenMediaType isEqual:(NSString *)kUTTypeImage]) {
        imageView.image = image;
        imageView.hidden = NO;
        moviePlayerController.view.hidden = YES;
        
        //save image to albums
        
        
        
        
        
        
    } else if ([lastChosenMediaType isEqual:(NSString *)kUTTypeMovie]) {
        [self.moviePlayerController.view removeFromSuperview];
        self.moviePlayerController = [[[MPMoviePlayerController alloc]
									   initWithContentURL:movieURL] autorelease];
        moviePlayerController.view.frame = imageFrame;
        moviePlayerController.view.clipsToBounds = YES;
        [self.view addSubview:moviePlayerController.view];
        imageView.hidden = YES;
    }
}

- (void)getMediaFromSource:(UIImagePickerControllerSourceType)sourceType {
    NSArray *mediaTypes = [UIImagePickerController
						   availableMediaTypesForSourceType:sourceType];
    if ([UIImagePickerController isSourceTypeAvailable:
         sourceType] && [mediaTypes count] > 0) {
        NSArray *mediaTypes = [UIImagePickerController
							   availableMediaTypesForSourceType:sourceType];
        UIImagePickerController *picker =
        [[UIImagePickerController alloc] init];
        picker.mediaTypes = mediaTypes;
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentModalViewController:picker animated:YES];
        [picker release];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:@"Error accessing media" 
                              message:@"Device doesn’t support that media source." 
                              delegate:nil 
                              cancelButtonTitle:@"Drat!" 
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

@end
